<?php

require_once("GenericWriter.php");

class DistrictWriter extends GenericWriter{
	
	public function __construct($object = NULL, $connection = NULL){
		parent::__construct($object, $connection);
	}
	
	public function save(){
		if(!is_null($this->object) && is_a($this->object, "District")){
			$insert = new RXInsert($this->connection);
			$insert->addTable("districts");
			$insert->addFieldValue("name", utf8_encode($this->object->getName()));
			$insert->addFieldValue("normalized_name", utf8_encode($this->object->getNormalizedName()));
			$insert->addFieldValue("town", $this->object->getTown()->getId());
			if($insert->execute()){
				return $insert->getLastInsertedId();
			}else{
				return FALSE;
			}		
		}else{
			return FALSE;
		}
	}
	
	public function delete(){
		if(!is_null($this->object) && is_a($this->object, "Districts")){
			$delete = new RXDelete($this->connection);
			$delete->addTable("districts");
			$delete->addWhereAndStatementEquals("id", $this->object->getId());
			return $delete->execute();
		}
	}
	
	public function update(){
		if(!is_null($this->object) && is_a($this->object, "Districts")){
			$update = new RXUpdate($this->connection);

			switch($this->operation){				
				case "UPDATE_TOWN": 
								$update->addTable("districts");
								$update->addField("town", $this->object->getTown()->getId());
				
				default: 	$update->addTable("districts");
								$update->addField("name", $this->object->getName());
								$update->addField("normalized_name", $this->object->getNormalizedName());
								$update->addWhereAndStatementEquals("id", $this->object->getId());
			}
			
			return $update->execute();
		}
	}	
}